package tbdp.tool.util;

import org.apache.commons.lang.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xbkaishui on 17/2/26.
 */
public class VariableUtils {

    public static String substituteVars(String format, Map<String, String> ctx) {
        Pattern formatPattern =
            Pattern.compile("\\$\\{([a-zA-Z0-9.,:\\#\\/\\=_\\-\\+\\(\\)\\ ]+)\\}");
        if (!StringUtils.isEmpty(format)) {
            Matcher matcher = formatPattern.matcher(format);

            if (matcher.find()) {
                String variableName = matcher.group(1);
                String variableValue = ctx.get(variableName);
                if (StringUtils.isNotEmpty(variableValue)) {
                    String formatNew = matcher.replaceFirst(variableValue);
                    return substituteVars(formatNew, ctx);
                }
            }
        }
        return format;
    }
}